#!/usr/bin/env bash
set -euo pipefail

# 框架演进驱动脚本（项目侧 ↔ 框架侧，按需）
# 作用：在配套模式下同步“非私有内容”（docs/rules/scripts/requirements[/config]）。
# 模式：
#   - verify：干跑（Dry Run），只检查是否需要演进；不修改任何文件；退出码非0表示需要执行 apply。
#   - apply：实际执行同步，并在项目侧与框架侧的 journal/milestones 记录迭代摘要。
# 选项：
#   --no-config：遵循 No-Config 策略，演进时跳过 config/ 目录。
# 用法示例：
#   bash scripts/framework_evolve.sh verify --no-config
#   bash scripts/framework_evolve.sh apply --no-config
# 备注：CI 在 push 与 PR gate 中默认使用 --no-config，以避免污染项目本地配置。

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
AID_DIR="$(dirname "$SCRIPT_DIR")"
ROOT_DIR="$(dirname "$AID_DIR")"

# 可选配置加载：尝试从框架 config 中读取环境键（不强制）
CONFIG_ENV="$AID_DIR/config/rules.env"
if [[ -f "$CONFIG_ENV" ]]; then
  # shellcheck disable=SC1090
  source "$CONFIG_ENV" || true
fi

# 镜像目录名称仅从配置/环境获取，不设默认值；框架名显示可保留默认
MIRROR_DIR_NAME="${MIRROR_DIR_NAME:-}"
# 优先使用配置中的 FRAMEWORK_DIR_NAME 作为名称显示；否则回退到 FRAMEWORK_NAME/AIDevFlow
FRAMEWORK_NAME="${FRAMEWORK_DIR_NAME:-${FRAMEWORK_NAME:-AIDevFlow}}"
TARGET_DIR=""
if [[ -n "$MIRROR_DIR_NAME" ]]; then
  TARGET_DIR="$ROOT_DIR/$MIRROR_DIR_NAME"
fi

MODE_ARG="${1:-verify}"
MODE="$MODE_ARG"

# Parse optional flags
if [[ $# -gt 0 ]]; then
  shift || true
fi

NO_CONFIG=false
EXTRA_ARGS=()
while [[ ${1:-} ]]; do
  case "$1" in
    --no-config|--no_config)
      NO_CONFIG=true
      EXTRA_ARGS+=("--no-config")
      ;;
    *)
      # ignore unknown flags for forward compatibility
      ;;
  esac
  shift || break
done

if [[ -z "$MIRROR_DIR_NAME" ]]; then
  echo "Framework mirror name not configured (skip)"
  exit 0
fi
if [[ ! -d "$TARGET_DIR" ]]; then
  echo "Framework mirror not found: $TARGET_DIR (skip)"
  exit 0
fi

case "$MODE" in
  verify|apply) : ;;
  *) echo "Invalid mode: $MODE (use verify|apply)"; exit 2;;
esac

append_journal() {
  local file_path="$1"
  local ts="$2"
  local direction="$3"
  local sync_paths="$4"
  local status="$5"
  local actor
  actor=$(git config user.name 2>/dev/null || echo "unknown")
  if [[ ! -f "$file_path" ]]; then
    mkdir -p "$(dirname "$file_path")"
    echo "# 框架迭代记录" > "$file_path"
    echo >> "$file_path"
  fi
  {
    echo "## [$ts] 框架演进应用"
    echo "- 方向: $direction"
    echo "- 变更路径: $sync_paths"
    echo "- 状态: $status"
    echo "- 触发者: $actor"
    echo
  } >> "$file_path"
}

append_milestone() {
  local file_path="$1"
  local ts="$2"
  local sync_paths="$3"
  local sha="$4"
  if [[ ! -f "$file_path" ]]; then
    mkdir -p "$(dirname "$file_path")"
    echo "# 框架里程碑" > "$file_path"
    echo >> "$file_path"
  fi
  {
    echo "### $ts 演进应用"
    echo "- commit: $sha"
    echo "- 变更范围: $sync_paths"
    echo
  } >> "$file_path"
}

SYNC_PATHS_LIST="docs, rules, scripts, tools/admin, requirements/aidevflow_evolution_requirements.md"
if [[ "$NO_CONFIG" != "true" ]]; then
  SYNC_PATHS_LIST="$SYNC_PATHS_LIST, config"
fi

if [[ "$MODE" == "verify" ]]; then
  # Delegate verify (legacy path)
  bash "$AID_DIR/scripts/sync_to_aidevflowmode.sh" verify ${EXTRA_ARGS[@]:-}
else
  # Check if evolution is needed first
  changed=0
  if bash "$AID_DIR/scripts/sync_to_aidevflowmode.sh" verify ${EXTRA_ARGS[@]:-}; then
    changed=0
  else
    changed=1
  fi

  # Gather changes list for summary (before apply)
  changes_list=""
  if [[ "$changed" -eq 1 ]]; then
    changes_list=$(bash "$AID_DIR/scripts/sync_to_aidevflowmode.sh" changes ${EXTRA_ARGS[@]:-} || true)
  fi

  # Apply evolution
  bash "$AID_DIR/scripts/sync_to_aidevflowmode.sh" apply ${EXTRA_ARGS[@]:-}

  # Log iteration only when actual changes existed
  if [[ "$changed" -eq 1 ]]; then
    ts="$(date "+%Y-%m-%d %H:%M:%S")"
    sha="$(git rev-parse --short HEAD 2>/dev/null || echo unknown)"
    # Update source-side journal (exists in docs)
    SRC_JOURNAL="$AID_DIR/docs/ai_devflow_journal.md"
    append_journal "$SRC_JOURNAL" "$ts" "$FRAMEWORK_NAME → $MIRROR_DIR_NAME" "$SYNC_PATHS_LIST" "mirror updated"
    # Update mirror-side journal (create if missing)
    MIRROR_JOURNAL="$TARGET_DIR/docs/ai_devflow_journal.md"
    append_journal "$MIRROR_JOURNAL" "$ts" "$FRAMEWORK_NAME → $MIRROR_DIR_NAME" "$SYNC_PATHS_LIST" "mirror updated"
    # Append milestones (source and mirror)
    SRC_MILESTONE="$AID_DIR/docs/milestones.md"
    MIRROR_MILESTONE="$TARGET_DIR/docs/milestones.md"
    append_milestone "$SRC_MILESTONE" "$ts" "$SYNC_PATHS_LIST" "$sha"
    append_milestone "$MIRROR_MILESTONE" "$ts" "$SYNC_PATHS_LIST" "$sha"
    echo "Logged iteration to: $SRC_JOURNAL and $MIRROR_JOURNAL"
    echo "Updated milestones: $SRC_MILESTONE and $MIRROR_MILESTONE"

    # Append diff summary to journals (limited to top 10 entries)
    if [[ -n "$changes_list" ]]; then
      total_count=$(echo "$changes_list" | grep -c . || true)
      docs_count=$(echo "$changes_list" | grep -c '^docs/' || true)
      rules_count=$(echo "$changes_list" | grep -c '^rules/' || true)
      scripts_count=$(echo "$changes_list" | grep -c '^scripts/' || true)
      tools_count=$(echo "$changes_list" | grep -c '^tools/' || true)
      config_count=$(echo "$changes_list" | grep -c '^config/' || true)
      req_count=$(echo "$changes_list" | grep -c '^requirements/' || true)
      top_entries=$(echo "$changes_list" | head -n 10)
      {
        echo "- 变更条目计数: $total_count (docs:$docs_count, rules:$rules_count, scripts:$scripts_count, tools:$tools_count, config:$config_count, requirements:$req_count)"
        echo "- Diff 摘要（最多10条）："
        echo "$top_entries" | sed 's/^/  - /'
        echo
      } >> "$SRC_JOURNAL"
      {
        echo "- 变更条目计数: $total_count (docs:$docs_count, rules:$rules_count, scripts:$scripts_count, tools:$tools_count, config:$config_count, requirements:$req_count)"
        echo "- Diff 摘要（最多10条）："
        echo "$top_entries" | sed 's/^/  - /'
        echo
      } >> "$MIRROR_JOURNAL"
    fi
  else
    echo "No changes detected; iteration journal not updated."
  fi
fi
